package com.rongke.web.controller.medical;

import com.alibaba.fastjson.JSONObject;
import com.rongke.commons.JsonResp;
import com.rongke.model.Chemotherapy;
import com.rongke.model.ChemotherapyMedicine;
import com.rongke.model.dict.DictMedicine;
import com.rongke.model.dict.DictMedicineUseType;
import com.rongke.service.ChemotherapyMedicineService;
import com.rongke.service.ChemotherapyService;
import com.rongke.service.DictMedicineService;
import com.rongke.service.DictMedicineUseTypeService;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ChemotherapyController
 * @化疗方案Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value = "/api/chemotherapy")
@Transactional
public class ChemotherapyController {
	private static final Logger LOGGER = Logger
			.getLogger(ChemotherapyController.class);

	@Autowired
	private ChemotherapyService chemotherapyService;

	@Autowired
	private ChemotherapyMedicineService chemotherapyMedicineService;

	@Autowired
	private DictMedicineService dictMedicineService;

	@Autowired
	private DictMedicineUseTypeService dictMedicineUseTypeService;

	/**
	 * @添加化疗方案
	 * @param chemotherapy
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public JsonResp addChemotherapy(@RequestBody Chemotherapy chemotherapy) {
		LOGGER.debug("addChemotherapy");

		try {
			chemotherapyService.insert(chemotherapy);
			Long id = chemotherapy.getId();

			List<ChemotherapyMedicine> medicineList = chemotherapy
					.getMedicineList();
			if (CollectionUtils.isNotEmpty(medicineList)) {
				for (ChemotherapyMedicine medicine : medicineList) {
					medicine.setChemotherapyId(id);
					// fillIdWithName(medicine);
					chemotherapyMedicineService.insert(medicine);
				}
			}

			JSONObject json = new JSONObject();
			json.put("id", chemotherapy.getId());
			return JsonResp.ok(json);
		} catch (Exception e) {
			LOGGER.error("addChemotherapy failed", e);
			// 手动回滚
			TransactionAspectSupport.currentTransactionStatus()
					.setRollbackOnly();
			return JsonResp.fa(null);
		}
	}

	/**
	 * @修改化疗方案
	 * @param chemotherapy
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public JsonResp updateChemotherapy(@RequestBody Chemotherapy chemotherapy) {
		LOGGER.debug("updateChemotherapy");

		try {
			chemotherapy.setGmtCreate(null);// 不修改创建时间
			chemotherapy.setGmtModified(new Date());
			chemotherapy.setPicContent(null);
			chemotherapy.setUserId(null);
			chemotherapy.setMedicalRecordId(null);
			chemotherapyService.updateById(chemotherapy);

			// 删除旧的用药信息
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("chemotherapy_id", chemotherapy.getId());
			chemotherapyMedicineService.deleteByMap(param);
			// 重新插入
			List<ChemotherapyMedicine> medicineList = chemotherapy
					.getMedicineList();
			if (CollectionUtils.isNotEmpty(medicineList)) {
				for (ChemotherapyMedicine medicine : medicineList) {
					medicine.setChemotherapyId(chemotherapy.getId());
					// fillIdWithName(medicine);
					chemotherapyMedicineService.insert(medicine);
				}
			}

			JSONObject json = new JSONObject();
			json.put("id", chemotherapy.getId());
			return JsonResp.ok(json);
		} catch (Exception e) {
			LOGGER.error("updateChemotherapy failed", e);
			// 手动回滚
			TransactionAspectSupport.currentTransactionStatus()
					.setRollbackOnly();
			return JsonResp.fa(null);
		}
	}

	@RequestMapping(value = "/del", method = RequestMethod.POST)
	public JsonResp delChemotherapyById(long id) {
		if (LOGGER.isInfoEnabled()) {
			LOGGER.info("delChemotherapyById, id=" + id);
		}

		try {
			chemotherapyService.deleteById(id);

			Map<String, Object> param = new HashMap<String, Object>();
			param.put("chemotherapy_id", id);
			chemotherapyMedicineService.deleteByMap(param);

			JSONObject json = new JSONObject();
			json.put("id", id);
			return JsonResp.ok(json);
		} catch (Exception e) {
			LOGGER.error("delChemotherapyById failed, id=" + id, e);
			// 手动回滚
			TransactionAspectSupport.currentTransactionStatus()
					.setRollbackOnly();
			return JsonResp.fa(null);
		}
	}

	/**
	 * @根据id查找化疗方案
	 * @param id
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/selectOne", method = RequestMethod.GET)
	public JsonResp selectChemotherapy(Long id) {
		LOGGER.debug("selectChemotherapy");
		try {
			Chemotherapy chemotherapy = chemotherapyService.selectById(id);
			if (null == chemotherapy) {
				return JsonResp.ok();
			}

			Map<String, Object> param = new HashMap<String, Object>();
			param.put("chemotherapy_id", id);
			List<ChemotherapyMedicine> medicineList = chemotherapyMedicineService
					.selectByMap(param);
			// for (ChemotherapyMedicine medicine : medicineList) {
			// fillinNameWithId(medicine);
			// }
			chemotherapy.setMedicineList(medicineList);

			return JsonResp.ok(chemotherapy);
		} catch (Exception e) {
			LOGGER.error("selectChemotherapy failed", e);
			return JsonResp.fa(null);
		}
	}

	@RequestMapping(value = "/selectAll", method = RequestMethod.GET)
	public JsonResp selectList(long medicalRecordId) {
		if (LOGGER.isInfoEnabled()) {
			LOGGER.info("selectList, medicalRecordId=" + medicalRecordId);
		}

		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("medical_record_id", medicalRecordId);
			List<Chemotherapy> result = chemotherapyService.selectByMap(params);

			// 查询列表时，不需要查询具体的用药情况
			return JsonResp.ok(result);
		} catch (Exception e) {
			LOGGER.error("selectList failed, medicalRecordId="
					+ medicalRecordId, e);
			return JsonResp.fa(null);
		}
	}

	// private ChemotherapyMedicine fillinNameWithId(ChemotherapyMedicine
	// medicine) {
	// if (null == medicine) {
	// return medicine;
	// }
	// // 将药物的ID转换成药物名字
	// List<DictMedicine> dictList = dictMedicineService.selectByMap(null);
	// String medicineId = medicine.getMedicineId();
	// for (DictMedicine dictMedicine : dictList) {
	// if (String.valueOf(dictMedicine.getId()).equals(medicineId)) {
	// medicine.setMedicineName(dictMedicine.getName());
	// }
	// }
	//
	// // 将用药类型的ID转换成用药类型名称
	// List<DictMedicineUseType> dictUseTypeList = dictMedicineUseTypeService
	// .selectByMap(null);
	// String medicineUserTypeId = medicine.getMedicineType();
	// for (DictMedicineUseType dictMedicineUseType : dictUseTypeList) {
	// if (String.valueOf(dictMedicineUseType.getId()).equals(
	// medicineUserTypeId)) {
	// medicine.setMedicineTypeName(dictMedicineUseType.getName());
	// }
	// }
	//
	// return medicine;
	// }
	//
	// private ChemotherapyMedicine fillIdWithName(ChemotherapyMedicine
	// medicine) {
	// if (null == medicine) {
	// return medicine;
	// }
	// // 将药物的ID转换成药物名字
	// List<DictMedicine> dictList = dictMedicineService.selectByMap(null);
	// String medicineName = medicine.getMedicineName();
	// for (DictMedicine dictMedicine : dictList) {
	// if (String.valueOf(dictMedicine.getName()).equals(medicineName)) {
	// medicine.setMedicineId(String.valueOf(dictMedicine.getId()));
	// }
	// }
	//
	// // 将用药类型的ID转换成用药类型名称
	// List<DictMedicineUseType> dictUseTypeList = dictMedicineUseTypeService
	// .selectByMap(null);
	// String medicineUserTypeName = medicine.getMedicineTypeName();
	// for (DictMedicineUseType dictMedicineUseType : dictUseTypeList) {
	// if (String.valueOf(dictMedicineUseType.getName()).equals(
	// medicineUserTypeName)) {
	// medicine.setMedicineType(String.valueOf(dictMedicineUseType
	// .getId()));
	// }
	// }
	//
	// return medicine;
	// }
}
